<?php

namespace api\modules\v1\models;

use Yii;
use api\common\models\Common;
use yii\web\NotFoundHttpException;
use yii\web\HttpException;
use yii\data\ActiveDataProvider;
use api\modules\v1\models\News;
use api\common\controllers\CommonController;
use api\common\models\Mar;
use yii\db\Expression;
use yii\helpers\Url;
use yii\data\Pagination;
use yii\web\Link;
class Opinion extends Common
{

    /**
     * @return array|string
     */
    public static function tableName()
    {
        return '{{%opinion_app}}';
    }


    public function rules()
    {
        return [
            ['title', 'required','message'=>'意见反馈标题不能为空'],
            ['title', 'string', 'min' => 2,  'max' => 100],

            ['content', 'required','message'=>'意见反馈内容不能为空'],
            ['content', 'string', 'min' => 2,  'max' => 500],
        ];
    }


    public function beforeSave($insert = true)
    {
        if ($this->isNewRecord) {
            $this->time = date('Y-m-d H:i:s',time());
            $this->isreply = 0;
            $this->reply_time = '';
            $this->uid = Yii::$app->user->identity->id;
        }
        return true;
    }

    /*
     * 获取意见列表
     * @param $id
     * @param $catid
     * @param $pid 上级id
     * @return array|\yii\db\ActiveRecord[]
     */
    public function getList(){
        $query = self::find();
        $query->where(['uid'=>Yii::$app->user->identity->id]);
        $query->select('o_id,uid,title,content,time,isreply,reply_time');
        $count = $query->count();
        $pagination = new Pagination(['totalCount' => $count]);
        $pagination->defaultPageSize = Yii::$app->params['page_size'];
        $data = $query->offset($pagination->offset)
            ->limit($pagination->limit)
            ->orderBy('isreply desc,o_id desc')
            ->all();
        $this->serializePagination($pagination);
        $pagination->defaultPageSize = Yii::$app->params['page_size'];
        $_data = [];
        $_data['items'] = $data;
        $_data['_links'] = $this->linksEnvelope;
        $_data['_meta'] = $this->metaEnvelope;
        return $_data;
    }



    /*
     * 单个反馈获取接口
     * @param $comment_id
     * @return mixed
     */
    public function getOne($o_id){
        if(!self::findOne(['o_id'=>$o_id,'uid'=>Yii::$app->user->identity->id])){
            throw new HttpException(401,'未找到该反馈信息',0);
        }
        $query = self::find();
        $query->where(['o_id'=>$o_id,'uid'=>Yii::$app->user->identity->id]);
        $data = $query->one();
        return $data;
    }


}
